package com.wanchuang.hepos.ui.page.home;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.google.protobuf.InvalidProtocolBufferException;
import com.wanchuang.architecture.utils.NetworkUtils;
import com.wanchuang.architecture.utils.Utils;
import com.wanchuang.hepos.R;
import com.wanchuang.hepos.bridge.data.repository.Apis;
import com.wanchuang.hepos.bridge.request.LoginRequestViewModel;
import com.wanchuang.hepos.bridge.state.home.ChangeJieSuanKaViewModel;
import com.wanchuang.hepos.databinding.FragmentChangeJieSuanKaBinding;
import com.wanchuang.hepos.net.NetworkManager;
import com.wanchuang.hepos.net.interfaces.OnRequestCallBack;
import com.wanchuang.hepos.proto.Connect;
import com.wanchuang.hepos.proto.Merchant;
import com.wanchuang.hepos.proto.PBPublicOuterClass;
import com.wanchuang.hepos.ui.LocationSelectActivity;
import com.wanchuang.hepos.ui.BankSelectActivity;
import com.wanchuang.hepos.ui.ZhiHangSelectActivity;
import com.wanchuang.hepos.ui.base.BaseFragment;

/**
 * 文件名 : HomeRootFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/12/24 16:20
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */
public class ChangeJieSuanKaFragment extends BaseFragment {
    private FragmentChangeJieSuanKaBinding mBinding;
    private ChangeJieSuanKaViewModel mViewModel;
    private LoginRequestViewModel mRequestViewModel;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(ChangeJieSuanKaViewModel.class);
        mRequestViewModel = ViewModelProviders.of(this).get(LoginRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_change_jie_suan_ka, container, false);
        mBinding = FragmentChangeJieSuanKaBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRequestViewModel.getErrorString().observe(this, s -> {
            hideProgress();
            showShortToast(s);
        });  // 错误返回
        mRequestViewModel.getResultString().observe(this, s -> {
            hideProgress();
            showLongToast(s);
            nav().navigateUp();
        });
        mRequestViewModel.getCodeString().observe(this, s -> {
            showShortToast(s);
            hideProgress();
            mViewModel.startCode.set(true);
        });

        mSharedViewModel.areaName.observe(this, s ->
                {
                    String[] strings = s.split(",");
                    mViewModel.mProvince = strings[0];
                    mViewModel.mCity = strings[1];
                    mViewModel.mCounty = strings[2];
                    mViewModel.bankAddress.set(mViewModel.mCounty);
                }
        );


        mSharedViewModel.bankName.observe(this, s ->
                {
                    String[] strings = s.split(",");
                    mViewModel.mBankCode = strings[0];
                    mViewModel.bankName.set(strings[1]);
                    mViewModel.banklianhang.set("");
                    mViewModel.bankzhihang.set("");
                }
        );


        mSharedViewModel.areaId.observe(this, s ->
                {
                    String[] strings = s.split(",");
                    mViewModel.mProvinceID = strings[0];
                    mViewModel.mCityID = strings[1];
                    mViewModel.mCountyID = strings[2];
                    mViewModel.banklianhang.set("");
                    mViewModel.bankzhihang.set("");
                }

        );
        mSharedViewModel.zhiHangName.observe(this, s -> {
            String[] strings = s.split(",");
            mViewModel.banklianhang.set(strings[0]);
            mViewModel.bankzhihang.set(strings[1]);
        });
    }

    public class ClickProxy {
        public void submit() {
            String name = mViewModel.name.get();
            if (TextUtils.isEmpty(name)) {
                showShortToast("请输入姓名");
                return;
            }
            String bankCardCode = mViewModel.bankCardCode.get();
            if (TextUtils.isEmpty(bankCardCode)) {
                showShortToast("请输入银行卡号码");
                return;
            }
            String phone = mViewModel.phone.get();
            if (TextUtils.isEmpty(phone)) {
                showShortToast("请输入银行预留手机号");
                return;
            }
            String code = mViewModel.code.get();
            if (TextUtils.isEmpty(code)) {
                showShortToast("请输入手机验证码");
                return;
            }
            showProgress();

            PBPublicOuterClass.get_form_token.Builder PbBuilder = PBPublicOuterClass.get_form_token.newBuilder();
            PbBuilder.setAction("change_settle");
            PBPublicOuterClass.get_form_token data = PbBuilder.build();
            NetworkManager.INSTANCE.post(Apis.get_form_token, data.toByteArray(), new OnRequestCallBack() {
                @Override
                public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                    PBPublicOuterClass.get_form_token resp = PBPublicOuterClass.get_form_token.parseFrom(bytes);
                    Merchant.address.Builder addBuilder = Merchant.address.newBuilder();
                    addBuilder.setProvince(mViewModel.mProvinceID).setProvinceName(mViewModel.mProvince);
                    addBuilder.setCity(mViewModel.mCityID).setProvinceName(mViewModel.mCity);
                    addBuilder.setArea(mViewModel.mCountyID).setAreaName(mViewModel.mCounty);
                    Merchant.merchant_settle.Builder builder = Merchant.merchant_settle.newBuilder();
                    builder.setSettleName(mViewModel.name.get());
                    builder.setBankCard(mViewModel.bankCardCode.get());
                    builder.setBankName(mViewModel.bankName.get());
                    builder.setBankCode(mViewModel.mBankCode);
                    builder.setAddress(addBuilder.build());
                    builder.setBankSub(mViewModel.bankzhihang.get());
                    builder.setChannel(mViewModel.banklianhang.get());
                    builder.setMobile(mViewModel.phone.get());
                    builder.setCaptcha(mViewModel.code.get());
                    NetworkManager.INSTANCE.postFormat(Apis.change_settle, builder.build().toByteArray(), resp.getFormToken(), new OnRequestCallBack() {
                        @Override
                        public void onOk(byte[] bytes) {
                        }

                        @Override
                        public void onError(int code, String errorMessage) {
                            hideProgress();
                            if (code == 200) {
                                showShortToast(errorMessage);
                                nav().navigateUp();
                            } else {
                                showShortToast(errorMessage);
                            }
                        }
                    });

                }

                @Override
                public void onError(int code, String errorMessage) {
                    showShortToast(errorMessage);
                }
            });


        }

        public void back() {
            nav().navigateUp();
        }

        public void selectLocation() {
            Intent intent = new Intent(mActivity, LocationSelectActivity.class);
            mActivity.startActivity(intent);
        }

        public void getbankName() {
            Intent intent = new Intent(mActivity, BankSelectActivity.class);
            mActivity.startActivity(intent);
        }

        public void selectZhiHang() {
            if (mViewModel.bankName.get().isEmpty()) {
                showShortToast("请先选择银行卡所属银行");
                return;
            }
            if (mViewModel.mProvince.isEmpty()) {
                showShortToast("请先选择开卡行所在地");
                return;
            }
            Intent intent = new Intent(mActivity, ZhiHangSelectActivity.class);
            intent.putExtra("bank_name", mViewModel.bankName.get());
            intent.putExtra("province", mViewModel.mProvince);
            intent.putExtra("city", mViewModel.mCity);
            intent.putExtra("county", mViewModel.mCounty);
            mActivity.startActivity(intent);
        }


        public void getCode() {
            String mPhone = mViewModel.phone.get();
            if (TextUtils.isEmpty(mPhone)) {
                showShortToast("请输入手机号码");
                return;
            }
            if (mPhone.length() != 11) {
                showShortToast("请输入11位手机号码");
                return;
            }
            if (TextUtils.isEmpty(mPhone)) {
                showShortToast("请输入手机号码");
                return;
            }
            showProgress();
            mRequestViewModel.getCode(mPhone, "5");
        }
    }


    @Override
    public void onStop() {
        if (Utils.isAppForeground() || !mSharedViewModel.isLoading.getValue()) {
            mViewModel.startCode.set(false);
        }
        super.onStop();
    }

}
